// 1. React核心库
import React, { useState, useEffect, useCallback } from 'react';

// 2. UI组件库
import { Card, Form, Input, Button, message, Spin, Space, Avatar, Descriptions } from 'antd';

// 3. 图标库
import { UserOutlined, EditOutlined, SaveOutlined, LockOutlined } from '@ant-design/icons';

// 4. 专业组件库
import { PageContainer, ProForm, ProFormText } from '@ant-design/pro-components';

// 7. 项目内部模块
import { apiClients } from '@/services/apiClient';
import { autoLoginInDev } from '@/utils/autoLogin';

// 8. 生成的类型定义
import type { UserProfile, UserProfileRequest } from '@/services/generated/src';

const ProfilePage: React.FC = () => {
  const [userInfo, setUserInfo] = useState<UserProfile | null>(null);
  const [loading, setLoading] = useState(false);
  const [editMode, setEditMode] = useState(false);
  const [passwordForm] = Form.useForm();

  // 获取用户信息
  const fetchUserInfo = useCallback(async () => {
    try {
      setLoading(true);
      await autoLoginInDev();
      const response = await apiClients.auth.authMeRetrieve();
      setUserInfo(response.data); // 手动提取data字段
    } catch (error) {
      message.error('获取用户信息失败');
      console.error('获取用户信息失败:', error);
    } finally {
      setLoading(false);
    }
  }, []);

  // 更新用户信息
  const handleUpdateProfile = async (values: UserProfileRequest) => {
    try {
      setLoading(true);
      await autoLoginInDev();
      const response = await apiClients.auth.authMeUpdate({
        userProfileRequest: values
      });
      setUserInfo(response.data); // 手动提取data字段
      setEditMode(false);
      message.success('个人信息更新成功');
    } catch (error) {
      message.error('更新失败');
      console.error('更新用户信息失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 修改密码
  const handleChangePassword = async (values: any) => {
    try {
      setLoading(true);
      await autoLoginInDev();
      await apiClients.auth.authMeChangePasswordCreate({
        changePasswordRequest: values
      });
      passwordForm.resetFields();
      message.success('密码修改成功');
    } catch (error) {
      message.error('密码修改失败');
      console.error('密码修改失败:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchUserInfo();
  }, [fetchUserInfo]);

  if (loading && !userInfo) {
    return (
      <PageContainer>
        <div style={{ textAlign: 'center', padding: '50px' }}>
          <Spin size="large" />
        </div>
      </PageContainer>
    );
  }

  return (
    <PageContainer
      title="个人资料"
      extra={
        <Button
          type={editMode ? 'default' : 'primary'}
          icon={editMode ? <SaveOutlined /> : <EditOutlined />}
          onClick={() => setEditMode(!editMode)}
        >
          {editMode ? '取消编辑' : '编辑资料'}
        </Button>
      }
    >
      <Space direction="vertical" size="large" style={{ width: '100%' }}>
        {/* 基本信息卡片 */}
        <Card title="基本信息" loading={loading}>
          {!editMode ? (
            // 查看模式
            <div style={{ display: 'flex', alignItems: 'flex-start', gap: '24px' }}>
              <Avatar size={80} icon={<UserOutlined />} />
              <div style={{ flex: 1 }}>
                <Descriptions column={2}>
                  <Descriptions.Item label="用户名">{userInfo?.username}</Descriptions.Item>
                  <Descriptions.Item label="全名">{userInfo?.full_name}</Descriptions.Item>
                  <Descriptions.Item label="邮箱">{userInfo?.email}</Descriptions.Item>
                  <Descriptions.Item label="姓">{userInfo?.last_name}</Descriptions.Item>
                  <Descriptions.Item label="名">{userInfo?.first_name}</Descriptions.Item>
                  <Descriptions.Item label="注册时间">
                    {userInfo?.date_joined ? new Date(userInfo.date_joined).toLocaleString() : '-'}
                  </Descriptions.Item>
                  <Descriptions.Item label="最后登录">
                    {userInfo?.last_login ? new Date(userInfo.last_login).toLocaleString() : '首次登录'}
                  </Descriptions.Item>
                  <Descriptions.Item label="账户状态">
                    {userInfo?.is_active ? '正常' : '已禁用'}
                  </Descriptions.Item>
                </Descriptions>
              </div>
            </div>
          ) : (
            // 编辑模式
            <ProForm
              initialValues={userInfo || {}}
              onFinish={handleUpdateProfile}
              submitter={{
                searchConfig: {
                  submitText: '保存',
                },
                resetButtonProps: {
                  style: { display: 'none' },
                },
              }}
            >
              <ProFormText
                name="email"
                label="邮箱"
                rules={[
                  { required: true, message: '请输入邮箱' },
                  { type: 'email', message: '请输入有效的邮箱地址' },
                ]}
              />
              <ProFormText
                name="first_name"
                label="名"
                rules={[{ required: true, message: '请输入名' }]}
              />
              <ProFormText
                name="last_name"
                label="姓"
                rules={[{ required: true, message: '请输入姓' }]}
              />
            </ProForm>
          )}
        </Card>

        {/* 修改密码卡片 */}
        <Card title="修改密码" extra={<LockOutlined />}>
          <Form
            form={passwordForm}
            layout="vertical"
            onFinish={handleChangePassword}
            style={{ maxWidth: 400 }}
          >
            <Form.Item
              name="old_password"
              label="当前密码"
              rules={[{ required: true, message: '请输入当前密码' }]}
            >
              <Input.Password placeholder="请输入当前密码" />
            </Form.Item>
            <Form.Item
              name="new_password"
              label="新密码"
              rules={[
                { required: true, message: '请输入新密码' },
                { min: 6, message: '密码至少6位' },
              ]}
            >
              <Input.Password placeholder="请输入新密码" />
            </Form.Item>
            <Form.Item
              name="new_password_confirm"
              label="确认新密码"
              dependencies={['new_password']}
              rules={[
                { required: true, message: '请确认新密码' },
                ({ getFieldValue }) => ({
                  validator(_, value) {
                    if (!value || getFieldValue('new_password') === value) {
                      return Promise.resolve();
                    }
                    return Promise.reject(new Error('两次输入的密码不一致'));
                  },
                }),
              ]}
            >
              <Input.Password placeholder="请再次输入新密码" />
            </Form.Item>
            <Form.Item>
              <Button type="primary" htmlType="submit" loading={loading}>
                修改密码
              </Button>
            </Form.Item>
          </Form>
        </Card>
      </Space>
    </PageContainer>
  );
};

export default ProfilePage;
